#include <iostream>
#include <string>
#include <memory>
#include <thread>
#include <chrono>
#include <csignal>

#include "EtherCATMaster.h"
#include "EtherCATConfig.h"

// 全局变量，用于控制程序运行
static bool running = true;

// 信号处理函数
void signalHandler(int signum) {
    std::cout << "\nInterrupt signal (" << signum << ") received." << std::endl;
    running = false;
}

int main(int argc, char* argv[]) {
    // 注册信号处理函数
    signal(SIGINT, signalHandler);
    
    // 配置文件路径
    std::string configFile = "ethercat.conf";
    
    // 如果提供了命令行参数，使用指定的配置文件
    if (argc > 1) {
        configFile = argv[1];
    }
    
    // 加载配置
    EtherCATConfig config(configFile);
    if (!config.loadConfig()) {
        std::cout << "Using default configuration" << std::endl;
        // 创建默认配置文件供将来使用
        config.saveConfig();
    }
    
    // 获取配置的主站类型和网络接口
    MasterType masterType = config.getMasterType();
    std::string ifname = config.getInterfaceName();
    
    std::cout << "Using " << (masterType == MasterType::IGH ? "IGH" : "SOEM") 
              << " EtherCAT master on interface " << ifname << std::endl;
    
    // 创建主站实例
    std::shared_ptr<EtherCATMaster> master = EtherCATMaster::createMaster(masterType);
    if (!master) {
        std::cerr << "Failed to create EtherCAT master" << std::endl;
        return 1;
    }
    
    // 初始化主站
    if (!master->init(ifname)) {
        std::cerr << "Failed to initialize EtherCAT master" << std::endl;
        return 1;
    }
    
    // 配置从站
    if (!master->configureSlaves()) {
        std::cerr << "Failed to configure slaves" << std::endl;
        return 1;
    }
    
    // 激活主站
    if (!master->activate()) {
        std::cerr << "Failed to activate EtherCAT master" << std::endl;
        return 1;
    }
    
    std::cout << "EtherCAT master activated successfully" << std::endl;
    std::cout << "Press Ctrl+C to exit" << std::endl;
    
    // 主循环
    while (running) {
        // 执行周期性任务
        master->cyclicTask();
        
        // 可以在这里添加应用程序特定的代码
        
        // 短暂休眠，避免CPU占用过高
        std::this_thread::sleep_for(std::chrono::milliseconds(1));
    }
    
    std::cout << "Shutting down EtherCAT master..." << std::endl;
    
    // 关闭主站
    master->shutdown();
    
    std::cout << "EtherCAT master shut down successfully" << std::endl;
    
    return 0;
}